//
//  DCCodeView.m
//  DCProject
//
//  Created by bigbing on 2019/12/12.
//  Copyright © 2019 bigbing. All rights reserved.
//

#import "DCCodeView.h"
#import "NHGraphCoder.h"

@interface DCCodeView ()

@property (nonatomic, strong) UIControl * control;
@property (nonatomic, strong) UIView * bgView;
@property (nonatomic, strong) NHGraphCoder * coder;

@end

@implementation DCCodeView

- (instancetype)initWithFrame:(CGRect)frame imageUrl:(NSString *)imageUrl{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpUI:frame imageUrl:imageUrl image:nil];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame imageUrl:(NSString *)imageUrl image:(UIImage *)image{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpUI:frame imageUrl:imageUrl image:image];
    }
    return self;
}


- (void)setUpUI:(CGRect)frame imageUrl:(NSString *)imageUrl image:(UIImage *)image
{
    self.backgroundColor = [UIColor dc_colorWithHexString:@"#333333" alpha:0.5];
    
    _control = [[UIControl alloc] initWithFrame:frame];
    [_control addTarget:self action:@selector(cancelControlClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_control];
    
    _bgView = [[UIView alloc] initWithFrame:CGRectZero];
    _bgView.backgroundColor = [UIColor whiteColor];
    [_bgView dc_cornerRadius:3];
    [self addSubview:_bgView];
    
    CGFloat width = 0.8*CGRectGetWidth(frame);
    CGFloat height = width * 0.52;
    if (image) {
        height = width * image.size.height/image.size.width;
    }
    
    WEAKSELF;
    self.coder = [NHGraphCoder codeWithURL:imageUrl frame:CGRectMake(0, 0, width, height + 68)];
    self.coder.center = CGPointMake(self.dc_centerX, self.dc_centerY);
    [self.coder handleGraphicCoderVerifyEvent:^(NHGraphCoder * _Nonnull cd, BOOL success) {
        
        [weakSelf removeFromSuperview];
        
        if (success) {
            if (weakSelf.successBlock) {
                weakSelf.successBlock();
            }
        }
    }];
    
    [self addSubview:self.coder];
    
    self.bgView.frame = CGRectMake((kScreenW - width - 20)/2, (kScreenH - height - 68)/2 - 10, width + 20, height + 68 + 10);
    
}


#pragma mark - 移除视图
- (void)cancelControlClick:(id)sender
{
    [self removeFromSuperview];
}
@end
